package com.zrkizzy.module.security.service;

import com.zrkizzy.common.models.domain.system.core.User;
import com.zrkizzy.common.redis.service.IRedisService;
import com.zrkizzy.common.security.utils.UserDetailUtil;
import com.zrkizzy.common.security.domain.LoginUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import static com.zrkizzy.common.redis.enums.RedisKey.USER_KEY;

/**
 * 用户加载业务逻辑
 *
 * @author zhangrongkang
 * @since 2023/3/10
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDetailUtil userDetailUtil;

    @Autowired
    private IRedisService redisService;

    @Override
    public LoginUserDetails loadUserByUsername(String traceId) throws UsernameNotFoundException {
        // 查看Redis中是否存在当前用户
        User user = redisService.get(USER_KEY.getKey() + traceId, User.class);
        // 2. 如果Redis中不存在当前用户信息则从数据库获取
        if (null == user) {
            log.error("未查询到User用户，traceId: {}", traceId);
            return null;
        }
        // 将获取到的用户对象转为UserDetails对象返回
        return userDetailUtil.convertUserDetails(user);
    }

}
